package com.hsjk.szwj.module.pay.controller.app.transfer;

import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.framework.common.util.spring.SpringBeansUtil;
import com.hsjk.szwj.module.pay.controller.AbstractPayOrderController;
import com.hsjk.szwj.module.pay.dal.dataobject.config.ChannelRetMsg;
import com.hsjk.szwj.module.pay.dal.dataobject.config.MchAppConfigContext;
import com.hsjk.szwj.module.pay.dal.dataobject.order.TransferOrderDO;
import com.hsjk.szwj.module.pay.dal.dataobject.system.MchAppDO;
import com.hsjk.szwj.module.pay.dal.dataobject.system.MchInfoDO;
import com.hsjk.szwj.module.pay.exception.ResponseException;
import com.hsjk.szwj.module.pay.service.ConfigContextQueryService;
import com.hsjk.szwj.module.pay.service.IMchAppService;
import com.hsjk.szwj.module.pay.service.IMchInfoService;
import com.hsjk.szwj.module.pay.service.ITransferNoticeService;
import com.hsjk.szwj.module.pay.service.PayMchNotifyService;
import com.hsjk.szwj.module.pay.service.TransferOrderService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/26 15:32
 **/
@Tag(name = "应用端 - 转账通知相关接口")
@RestController
@RequestMapping("/transfer")
@Validated
@Slf4j
public class TransferNoticeController extends AbstractPayOrderController {
    @Resource
    private TransferOrderService transferOrderService;
    @Resource
    private ConfigContextQueryService configContextQueryService;
    @Resource
    private PayMchNotifyService payMchNotifyService;
    @Resource
    private IMchInfoService mchInfoService;
    @Resource
    private IMchAppService mchAppService;

    /**
     * 异步回调入口
     **/
    @ResponseBody
    @RequestMapping(value = {"/notify/{ifCode}",
            "/notify/{ifCode}/{transferId}"})
    public ResponseEntity doNotify(HttpServletRequest request,
                                   @PathVariable("ifCode") String ifCode,
                                   @PathVariable(value = "transferId", required = false)
                                           Long urlOrderId) {

        Long transferId = null;
        String logPrefix = "进入[" + ifCode + "]转账回调：urlOrderId：[" +
                StringUtils.defaultIfEmpty(String.valueOf(urlOrderId), "") + "] ";
        log.info("===== {} =====", logPrefix);

        try {

            // 参数有误
            if (StringUtils.isEmpty(ifCode)) {
                return ResponseEntity.badRequest().body("ifCode is empty");
            }

            //查询转账接口是否存在
            ITransferNoticeService transferNotifyService
                    = SpringBeansUtil.getBean(ifCode + "TransferNoticeService",
                    ITransferNoticeService.class);

            // 支付通道转账接口实现不存在
            if (transferNotifyService == null) {
                log.error("{}, transfer interface not exists ", logPrefix);
                return ResponseEntity.badRequest()
                        .body("[" + ifCode + "] transfer interface not exists");
            }

            // 解析转账单号 和 请求参数
            MutablePair<Long, Object> mutablePair
                    = transferNotifyService.parseParams(request, urlOrderId);
            if (mutablePair == null) {
                // 解析数据失败， 响应已处理
                log.error("{}, mutablePair is null ", logPrefix);
                //需要实现类自行抛出ResponseException, 不应该在这抛此异常。
                throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                        "解析数据异常！");
            }

            // 解析到转账单号
            transferId = mutablePair.left;
            log.info("{}, 解析数据为：transferId:{}, params:{}",
                    logPrefix, transferId, mutablePair.getRight());

            // 获取转账单号 和 转账单数据
            TransferOrderDO transferOrder = transferOrderService.getById(transferId);

            // 转账单不存在
            if (transferOrder == null) {
                log.error("{}, 转账单不存在. transferId={} ", logPrefix, transferId);
                return transferNotifyService.doNotifyOrderNotExists(request);
            }
            MchInfoDO mchInfoDO = mchInfoService.getMchInfoById(transferOrder.getMchId());
            MchAppDO mchAppDO = mchAppService.getById(transferOrder.getAppId());
            //查询出商户应用的配置信息
            MchAppConfigContext mchAppConfigContext
                    = configContextQueryService.queryMchInfoAndAppInfo(mchInfoDO.getId(),
                    mchAppDO.getId());

            //调起接口的回调判断
            ChannelRetMsg notifyResult = transferNotifyService.doNotice(request, mutablePair.getRight(), transferOrder, mchAppConfigContext);

            // 返回null 表明出现异常， 无需处理通知下游等操作。
            if (notifyResult == null || notifyResult.getChannelState() == null || notifyResult.getResponseEntity() == null) {
                log.error("{}, 处理回调事件异常  notifyResult data error, notifyResult ={} ", logPrefix, notifyResult);
                throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                        "处理回调事件异常！"); //需要实现类自行抛出ResponseException, 不应该在这抛此异常。
            }

            // 转账单是 【转账中状态】
            if (transferOrder.getState() == TransferOrderDO.STATE_ING) {
                if (notifyResult.getChannelState()
                        == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) {
                    // 转账成功
                    transferOrderService.updateIng2Success(transferId,
                            notifyResult.getChannelOrderId());
                    payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId));

                } else if (notifyResult.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL) {
                    // 转账失败
                    transferOrderService.updateIng2Fail(transferId,
                            notifyResult.getChannelOrderId(), notifyResult.getChannelUserId(),
                            notifyResult.getChannelErrCode());
                    payMchNotifyService.transferOrderNotify(transferOrderService.getById(transferId));
                }
            }

            log.info("===== {}, 转账单通知完成。 transferId={}, parseState = {} =====", logPrefix, transferId, notifyResult.getChannelState());

            return notifyResult.getResponseEntity();

        } catch (ServiceException e) {
            log.error("{}, transferId={}, BizException", logPrefix, transferId, e);
            return ResponseEntity.badRequest().body(e.getMessage());

        } catch (ResponseException e) {
            log.error("{}, transferId={}, ResponseException", logPrefix, transferId, e);
            return e.getResponseEntity();

        } catch (Exception e) {
            log.error("{}, transferId={}, 系统异常", logPrefix, transferId, e);
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}
